<?php
namespace App\Model;

use Illuminate\Database\Eloquent\Model;
use Spatie\MediaLibrary\HasMedia\HasMedia;
use Spatie\MediaLibrary\HasMedia\HasMediaTrait;

class Order extends Model implements HasMedia
{

    use HasMediaTrait;

    protected $table = 'orders';


    /**
     * 获取订单商品
     */
    public function orderGoods()
    {
        return $this->hasMany('App\Model\OrderGoods', 'order_id', 'id')->with('goods');
    }

    /**
     * 获取用户
     */
    public function user(){
        return $this->hasOne('App\Model\User', 'id', 'user_id');
    }

    /**
     * 获取订单 order_sn
     * @return string
     */
    public function get_order_sn()
    {
        $order_sn = null;
        // 保证不会有重复订单号存在
        while(true){
            $order_sn = date('YmdHis').rand(1000,9999); // 订单编号
            $order_sn_count = Order::where('order_sn', $order_sn)->count();
            if($order_sn_count == 0)
                break;
        }

        return $order_sn;
    }
}